package com.weibo.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.weibo.common.util.FaceFormat;
import com.weibo.common.util.PageResult;
import com.weibo.dao.FriendMapper;
import com.weibo.dao.UserDao;
import com.weibo.dao.WeiboTabMapper;
import com.weibo.pojo.Message;
import com.weibo.pojo.User;
import com.weibo.pojo.WeiboTabExample;
import com.weibo.pojo.WeiiBoPojo;
import com.weibo.service.FriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 好友模块的服务层
 * @className FriendServiceImpl
 * @author 天火
 * @date 2019-03-12
 * @version 1.0
 */
@Service
public class FriendServiceImpl implements FriendService {

    @Autowired
    private FriendMapper friendMapper;

    @Autowired
    private WeiboTabMapper weiboTabMapper;

    @Autowired
    private UserDao userDao;



    @Override
    public PageResult findFriendWeibo(long uId, Integer pageNum) {
        List<Long> ids = friendMapper.findFriendByuId(uId);
        PageHelper.startPage(pageNum,5);

        WeiboTabExample example = new WeiboTabExample();
        WeiboTabExample.Criteria criteria = example.createCriteria();
        criteria.andUIdIn(ids);
        example.setOrderByClause("m_date DESC");
        List<WeiiBoPojo> weiiBoPojos = weiboTabMapper.selectByExample(example);
        weiiBoPojos = FaceFormat.formt(weiiBoPojos);            //格式微博信息
        for(WeiiBoPojo weibo :weiiBoPojos){

            if(weibo.getmLike()>0){
                weibo.setB(true);
            }
            else {
                weibo.setB(false);
            }
            User user = userDao.findUserById(weibo.getuId());
            weibo.setUser(user);
        }
        Page<WeiiBoPojo> pageWeibo = (Page<WeiiBoPojo>) weiiBoPojos;
        PageResult pageResult = new PageResult();
        pageResult.setTotals((int)pageWeibo.getTotal());
        pageResult.setPageTotals(pageWeibo.getPages());

        pageResult.setRows(pageWeibo.getResult());
        return pageResult;
    }

    @Override
    public int findAttentionUserNum(long id) {
        int attentionUserNum = 0;
        try {
            attentionUserNum = friendMapper.findAttentionNumByUserId(id);

        }catch (Exception e){
            e.printStackTrace();
        }
        return attentionUserNum;
    }

    @Override
    public PageResult findAttentionUserListByUserId(Long uId,int pageNum) {
        PageHelper.startPage(pageNum,10);
        List<User> users = friendMapper.findAttUser(uId);
        Page<User> pageUser = (Page<User>) users;
        PageResult pageResult = new PageResult();
        pageResult.setTotals((int)pageUser.getTotal());
        pageResult.setPageTotals(pageUser.getPages());
        pageResult.setRows(users);
        return pageResult;
    }

    @Override
    public User operationUser(String operation, User aUser, User bUser){
        User user = null;
        long aId = aUser.getId();
        long bId = bUser.getId();
        try {
            if(operation.equals("attention") ){
                //关注用户操作
                friendMapper.addAttentionUser(aId,bId);
                aUser.setAttention(aUser.getAttention()+1);		//a用户关注数+1
                bUser.setFans(bUser.getFans()+1);		//b用户粉丝数+1
            }else if(operation.equals("unsubscribe")){
                //取消关注用户操作
                friendMapper.unsubscribeUser(aId,bId);
                aUser.setAttention(aUser.getAttention()-1);		//a用户关注数-1
                bUser.setFans(bUser.getFans()-1);		//b用户粉丝数-1
            }else if(operation.equals("LH")){
                //拉黑用户 不接收该用户的私信
                friendMapper.updateFriendToBlack(aId, bId ,99);
                friendMapper.updateFriendState(aId, bId, 99);
                friendMapper.updateFriendToBlack(bId, aId ,99);
                friendMapper.updateFriendState(bId, aId, 99);
            }else if(operation.equals("QXLH")){
                //取消拉黑用户
                friendMapper.updateFriendToBlack(aId, bId ,0);
                friendMapper.updateFriendState(aId, bId, 0);
                friendMapper.updateFriendToBlack(bId, aId ,0);
                friendMapper.updateFriendState(bId, aId, 0);
            }
            userDao.updateUserInfo(aUser);
            userDao.updateUserInfo(aUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }


    @Override
    public Map<String, Object> findMessageNOReadById(Long aId, Long bId) {
        Map<String ,Object> map = new HashMap<>();
        try{
            List<User> users = friendMapper.findUserByUserId(aId);
            if(bId ==0 && users.size()!=0){
                bId = users.get(0).getId();
            }
            List<Message> messages = friendMapper.findUserMessageByUserId(aId,bId);
            for(int i=0;i<messages.size(); i++){
                messages.get(i).setUserA(userDao.findUserById(messages.get(i).getUserAId()));
                messages.get(i).setUserB(userDao.findUserById(messages.get(i).getUserBId()));
            }
            messages = FaceFormat.messageFormt(messages);
            User user = userDao.findUserById(bId);
            for(int i=0;i<users.size();i++){
                //查找来自该用户的未读私信
                users.get(i).setUnReadMessage(friendMapper.findUnReadMessageByUserId(aId, users.get(i).getId()));
            }
            map.put("list",messages);
            map.put("bUser",user);
            map.put("attUsers",users);

            //设置私信信息为已读
            friendMapper.setMessageRead(aId, bId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 插入消息和检查是否被拉黑
     *
     * @param message 消息
     */
    @Override
    public void sendMessage(Message message) {
        try{
            Long state = friendMapper.findFriendState(message.getUserAId(),message.getUserBId());
            if(state==99){
                message.setState(99);
            }
            Date date = new Date();
            message.setMessageDate(date);
            friendMapper.insertMessage(message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 根据用户ID查询粉丝
     * @param userId 用户Id
     * @return 用户集合
     */
    @Override
    public PageResult findFansByUserId(Long userId,Integer pageNum) {
        //注入mapper
        //使用mapper方法
        PageResult result = new PageResult();
        try{
            PageHelper.startPage(pageNum,10);
            List<User> users = friendMapper.findFansByUserId(userId);
            Page<User> userPage = (Page<User>) users;

            result.setRows(userPage.getResult());
            result.setTotals((int)userPage.getTotal());
            result.setPageTotals(userPage.getPages());
        }catch(Exception e){
            e.printStackTrace();;
        }
        return result;
    }

    @Override
    public PageResult findBlacksUserByUserId(Long userId, Integer pageNum) {
        //注入mapper
        //使用mapper方法
        PageResult result = new PageResult();
        try{
            PageHelper.startPage(pageNum,10);
            List<User> users = friendMapper.findBlacksUserByUserId(userId);
            Page<User> userPage = (Page<User>) users;

            result.setRows(userPage.getResult());
            result.setTotals((int)userPage.getTotal());
            result.setPageTotals(userPage.getPages());
        }catch(Exception e){
            e.printStackTrace();;
        }
        return result;
    }


}
